<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    //? 尾节流：是指在时间间隔内的最后一次触发事件时执行函数，然后在间隔时间内忽略所有的触发事件。
    function throttleLast(fn,delay) {
        let timer = null
        let time = Date.now()
        return function (...args) {
            const now = Date.now()
            //? 还在时间间隔内
            if (now - time < delay) {
                if (timer) {
                    clearTimeout(timer)
                    timer = null
                }
                //? 在时间间隔内最后一次触发事件 说明这次的timer不会被更换，能够执行
                timer = setTimeout(() => {
                    fn(...args)
                },delay + time - now)
            }
        }
    }
    function testThrottleLast() {
        console.log('throttleLast test start');
        const throttleFunc = throttleLast(function() {
            console.log('throttleLast function called');
        }, 1000);
        throttleFunc();
        setTimeout(throttleFunc, 500);
        setTimeout(throttleFunc, 1000);
        setTimeout(throttleFunc, 1500);
        setTimeout(throttleFunc, 3500);
    }
    testThrottleLast();
</script>
</body>
</html>
